package com.lh_travel.lohas.activity.user;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.AvaterBean;
import com.lh_travel.lohas.domain.DafultMessageEvent;
import com.lh_travel.lohas.domain.UserBean;
import com.lh_travel.lohas.utils.ImageUtils;
import com.lh_travel.lohas.utils.PhotoUtil;
import com.lh_travel.lohas.utils.Preferences;
import com.lh_travel.lohas.widget.CircleImageView;
import com.squareup.picasso.Picasso;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.ResponseBody;
import rx.Subscriber;

public class UserInfoActivity extends baseActivity {

    private LinearLayout ll_avater;
    private Toolbar toolbar;
    private ImageButton img_back;
    private Bitmap bit;
    private boolean submitPic;
    private CircleImageView cimg_avater;
    private MyThread myThread;
    private String imgAddress;
    private EditText ed_name;
    private EditText ed_sign;
    private Button btn_confirm;
    private UserBean userBean;
    private RadioButton rb_1;
    private RadioButton rb_2;

    @SuppressLint("HandlerLeak")
    private Handler uiHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    submitPic = true;

                    String path = (String) msg.obj;

                    cimg_avater.setImageBitmap(BitmapFactory.decodeFile(path));

                    new api(mContext).avatar(path, userBean.token, new Subscriber() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(java.lang.Throwable e) {

                        }

                        @Override
                        public void onNext(Object o) {

                            ResponseBody body = (ResponseBody) o;

                            try {
                                String json = body.string();

                                AvaterBean result = new Gson().fromJson(json, new TypeToken<AvaterBean>() {
                                }.getType());

                                if (result.code.equals("200")){
                                    imgAddress = result.data.avatar;

                                    Log.e("sss", imgAddress);
                                }

                            } catch (IOException e) {

                                e.printStackTrace();
                            }
                        }

                    });

                    break;

            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_userinfo);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        img_back = (ImageButton) findViewById(R.id.img_back);

        ll_avater = (LinearLayout) findViewById(R.id.ll_avater);
        cimg_avater = (CircleImageView) findViewById(R.id.cimg_avater);
        ed_name = (EditText) findViewById(R.id.ed_name);
        ed_sign = (EditText) findViewById(R.id.ed_sign);
        rb_1 = (RadioButton) findViewById(R.id.rb_1);
        rb_2 = (RadioButton) findViewById(R.id.rb_2);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
    }

    @Override
    public void bindListner() {
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ll_avater.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                PhotoUtil.selectPictureFromAlbum(UserInfoActivity.this);

            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (submitPic && imgAddress == null) {
                    showMessage("头像正在上传");

                } else if (ed_name.getText().toString().trim().length() >= 20) {
                    showMessage("昵称不可以超过20字");

                } else if (ed_sign.getText().toString().trim().length() >= 100) {
                    showMessage("签名不可以超过100字");

                } else {
                    showViewLoad();
                    new api(mContext).editInfo(userBean.token, ed_name.getText().toString().trim(), rb_1.isChecked() ? 1 : 2, ed_sign.getText().toString().trim(), new RxResultCallback<Object>() {
                        @Override
                        public void onError(Object tag, Throwable e) {
                            dismissViewLoad();
                        }

                        @Override
                        public void onCancel(Object tag, Throwable e) {
                            dismissViewLoad();
                        }

                        @Override
                        public void onNext(Object tag, int code, String message, Object response) {

                            if (code == 200) {
                                dismissViewLoad();

                                DafultMessageEvent event = new DafultMessageEvent();
                                event.TAG = "LoginActivity";

                                EventBus.getDefault().post(event);

                                finish();
                            }

                            showMessage(message);

                        }
                    });
                }
            }
        });
    }

    @Override
    public void ensureUI() {

        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);

        userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);

        String LOGINTYPE = mApp.getPreference(Preferences.LOCAL.LOGINTYPE);

        switch (LOGINTYPE) {

            case "1":

                if (userBean.avatar.length() > 0) {

                    Picasso.with(mContext).load(userBean.avatar).
                            placeholder(R.drawable.default120).
                            error(R.drawable.default120).
                            fit().centerCrop().
                            into(cimg_avater);

                }

                ed_name.setText(userBean.nickname.length() > 0 ? userBean.nickname : "uid" + userBean.uid);
                ed_sign.setText(userBean.sign);

                break;

            case "2":


                Picasso.with(mContext).load(userBean.qq_avatar).
                        placeholder(R.drawable.default120).
                        error(R.drawable.default120).
                        fit().centerCrop().
                        into(cimg_avater);

                ed_name.setText(userBean.qq_nick);
                ed_sign.setText(userBean.sign);

                break;

            case "3":

                Picasso.with(mContext).load(userBean.wx_avatar).
                        placeholder(R.drawable.default120).
                        error(R.drawable.default120).
                        fit().centerCrop().
                        into(cimg_avater);

                ed_name.setText(userBean.wx_nick);

                ed_sign.setText(userBean.sign);

                break;
        }

        if (userBean.sex == 2){

            rb_2.setChecked(true);

        }else {
            rb_1.setChecked(true);
        }



    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            // 读取相册缩放图片
            case PhotoUtil.PHOTOZOOM:

                try {

                    Uri uri = data.getData();
                    bit = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

                    myThread = new MyThread(bit, uiHandle);

                    myThread.start();

                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (myThread != null) {

            bit = null;
            myThread.close();
        }

        uiHandle.removeCallbacksAndMessages(null);
    }

    private static class MyThread extends Thread {

        private boolean mRunning = false;
        private Bitmap bitmap;
        private Handler uiHandle;

        public MyThread(Bitmap bit, Handler handler) {
            this.bitmap = bit;
            this.uiHandle = handler;
        }

        @Override
        public void run() {
            mRunning = true;

            String bitmap = ImageUtils.compressImage(this.bitmap, "lohasuseravater", 100);

            Message msg = uiHandle.obtainMessage();

            msg.what = 1;

            msg.obj = bitmap;

            uiHandle.sendMessage(msg);
        }

        public void close() {
            mRunning = false;
        }
    }
}
